# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： cmdb
Description :
Author : 'li'
date： 6/26/2024
-------------------------------------------------
Change Activity:
6/26/2024:
-------------------------------------------------
"""
from modules.blk.cmdb.cmdb_service import CMDBService
from projects.inspection.network_device_inspection.utils.passwd_encode import decode_string


def load_device_login_info(inspection_area):
    """
    load device login information from cmdb
    Returns:

    """
    data = CMDBService().select('device_login_information')
    data = data['data']['info']
    format_data = []
    for d in data:
        for area in inspection_area:
            if d['data_center'] is None or area not in d['data_center']:
                continue
            format_d = dict(
                ip=d['IP_address'],
                connection_type=d['line_type'],
                brand=d['brand'],
                port=d['port'],
                dc_name=d['data_center'],
                device_model=d['device_model'],
                username=d['user_name'],
                password=decode_string(d['password'])
            )
            format_data.append(format_d)
    return format_data


def load_inspection_commands():
    """
    load inspection commands
    Returns:

    """
    data = CMDBService().select('network_inspection_instructions')
    data = data['data']['info']
    format_data = {}
    for d in data:
        brand = d['brand']
        if brand not in format_data:
            format_data[brand] = {}
        device_model = d['device_model']
        if device_model not in format_data[brand]:
            format_data[brand][device_model] = _format_instructions(d['device_instruct'])
    return format_data


def _format_instructions(instructions):
    """
    format instructions
    Args:
        instructions:

    Returns:

    """
    ins = {}
    if instructions is not None and len(instructions) > 0:
        lines = instructions.split('\n')
        for line in lines:
            if ":" not in line:
                continue
            command_name, command = line.split(':')[:2]
            if len(command_name) > 0 and len(command) > 0:
                ins[command_name] = command
    return ins
